package cn.gz.ibix.ibix_library.http;

import com.google.common.collect.Maps;

import java.util.Map;

import cn.gz.ibix.ibix_library.bean.ApiConfig;
import cn.gz.ibix.ibix_library.bean.ApiConfigManager;
import cn.gz.ibix.ibix_library.bean.RequestParamImpl;
import cn.gz.ibix.library.http.BaseHttpUtil;
import cn.gz.ibix.library.http.RequestParam;
import io.reactivex.Flowable;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Predicate;

/**
 * 项目名称：android_tool
 * <br>类描述：
 * <br>创建人：htliu
 * <br>创建时间：2018/4/25 9:39
 * <br>修改人:
 * <br>修改时间：2018/4/25 9:39
 * <br>修改备注：
 * <br>@version
 */

public class HttpUtil extends BaseHttpUtil {
    private ApiConfigManager apiConfigManager = ApiConfigManager.getInstance();
    private ApiConfig apiConfig = apiConfigManager.getApiConfig();

    private HttpUtil() {
    }

    public static HttpUtil getInstance() {
        return SingletonHolder.INSTANCE;
    }

    @Override
    protected String getBaseUrl() {
        return apiConfig.getBaseUrl();
    }

    @Override
    protected String getUrl(RequestParam requestParam) {
        if (requestParam instanceof RequestParamImpl) {
            RequestParamImpl requestParam1 = (RequestParamImpl) requestParam;
            String url = Flowable.fromArray(
                    getBaseUrl(),
                    apiConfig.getPrefixMap().get(requestParam1.server()),
                    requestParam.api()).filter(new Predicate<String>() {
                @Override
                public boolean test(String s) throws Exception {
                    return s != null && s.length() > 0;
                }
            }).reduce(new BiFunction<String, String, String>() {
                @Override
                public String apply(String s, String s2) throws Exception {
                    return s + s2;
                }
            }).blockingGet();
            return url;
        } else {
            return super.getUrl(requestParam);
        }
    }

    @Override
    protected Map<String, String> headers() {
        return Maps.newHashMap();
    }

    private static class SingletonHolder {
        private static final HttpUtil INSTANCE = new HttpUtil();
    }
}
